from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource,marshal,reqparse
import json
from models.users import Channel,News,UserModel,Collection
from common.model_fields.user import channel_fields,news_fields
from common.uitils.login_utils import login_required
from models import db

channel_bp = Blueprint('channel',__name__,)

api = Api(channel_bp)


class ChannelsResource(Resource):
    def get(self):
        """获取所有的频道信息"""
        channels = Channel.query.all()
        return marshal(channels, channel_fields)


class NewsByChannel(Resource):
    def get(self):
        """根据文章的id 获取文章信息"""
        parser = reqparse.RequestParser()
        parser.add_argument('category')
        args = parser.parse_args()
        cate_id = args.get('category')
        news = News.query.filter_by(channel_id=cate_id).all()
        # 把有序字典转成字典,然后给每篇文章添加作者信息
        datas = json.loads(json.dumps(marshal(news,news_fields)))

        for new in datas:
            user = UserModel.query.filter_by(uid=new['user_id']).first()
            new['nick_name'] = user.uname
        print('news_datas', datas)
        return jsonify(message='ok',code=200, data={'news': datas})


# 文章详情
class NewInfo(Resource):
    @login_required
    def get(self,id):
        """根据文章id 获取文章详情"""
        new = News.query.filter_by(nid=id).first()
        # 把有序字典转成字典,然后给每篇文章添加作者信息
        data = json.loads(json.dumps(marshal(new, news_fields)))
        user = UserModel.query.filter_by(uid=new.user_id).first()
        data['nick_name'] = user.uname
        data['has_follow'] = False
        data['has_star'] = False

        uid = g.user_id
        # 判断文章是否被收藏
        user_news = Collection.query.filter_by(user_id=uid,news_id=id).first()
        if user_news:
            data['has_star'] = True

        # 从评论中获取
        comment_data = [{'id':i.cmid, 'art_id':i.article_id,
                         'like_count':i.like_count,
                         "reply_count":i.reply_count,
                         'content':i.content,
                         'comment_length':len(new.comment)} for i in new.comment]
        data['comment'] = comment_data
        return jsonify(message='ok',code=200, data=data)


class CollectionListResource(Resource):
    @login_required
    def get(self,pk):
        """
        用户收藏文章
        """
        try:
            uid = g.user_id
            if not uid:
                return jsonify(message='请重新登录', code=204)
            collection = Collection(user_id=uid, news_id = pk)
            db.session.add(collection)
            db.session.commit()
            return jsonify(message='收藏成功', code=200)
        except Exception as e:
            print("收藏的错误>>>", e)
            return jsonify(message='服务器错误', code=500)


# 收藏
api.add_resource(CollectionListResource, '/collection/<int:pk>')
api.add_resource(ChannelsResource,'/channels')
api.add_resource(NewsByChannel,'/channel')
api.add_resource(NewInfo, '/info/<int:id>')